#include "../main.h"


//////////////////////////////////////////////////////////////////////////////
//
static JSBool js_tcpsocket(JSContext *cx, uintN argc, jsval *vp) {
	uint32 port;
	jsval func;
	
	trace1("tcpsocket");

	JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "u", &port);
	
	if (!JS_ConvertValue(cx, JS_ARGV(cx, vp)[1], JSTYPE_FUNCTION, &func))
		return JS_FALSE;

	int s, c, n, i=1;
	struct sockaddr_in sa;
	struct sockaddr_in cli;
//	fd_set sockfds;
//	struct timeval tv;
//	char buf1[256], buf2[256];
//	struct sockaddr_in my_addr;
//	struct sockaddr_in socks[50];
	s=socket(PF_INET, SOCK_STREAM, 0);
	bzero(&sa, sizeof sa);
	sa.sin_family = AF_INET;
	sa.sin_port   = htons(port);
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	i=1;
	setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int));
	bind(s, (struct sockaddr *)&sa, sizeof sa);
	trace2("listening");
	listen(s, 100);
	while(1){
		n=sizeof(cli);
		trace2("waiting for a new connection");
		if((c=accept(s,(struct sockaddr *)&cli, &n)) < 0)
			fatal("accept()");
		trace2("FD %i: accept with new thread", c);
		if(!create_js_thread(cx, func, c))
			fatal("create_js_thread()");		
	}
	return JS_TRUE;
}



int module_socket_init(JSContext *cx, JSObject *obj){
	JS_DefineFunction(cx, obj, "tcpsocket", (void *)js_tcpsocket, 2, JSFUN_FAST_NATIVE);
}
